import Vue from 'vue'
import Vuex from 'vuex'
import { getMenuList } from '../api/login';
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isCollapse:false,
    menuList:[],
    routerList:[],
    activeTab: '1',
    tabList: [
        {
            title: '首页',
            name: '1',
            // content: 'Tab 1 content'
        }
    ],
  },
  mutations: {
    changeCollapse(state){
      state.isCollapse = !state.isCollapse;
      console.log(state.isCollapse);
    },
    setActiveTab(state,name){
      state.activeTab = name;
      sessionStorage.setItem('tabObject',JSON.stringify({
        'tabList':state.tabList,
        'activeTab':state.activeTab
      }))
    },
    addTabList(state,tab){
      let index = state.tabList.findIndex(item=>item.name ==tab.name)
      console.log(index);
      if(index == -1){
        let obj = {};
        obj.title = tab.label;
        obj.name = tab.name;
        // obj.content = tab.label;
        state.tabList.push(obj)
      }
      state.activeTab = tab.name;
      console.log("!!"+state.activeTab);
      sessionStorage.setItem('tabObject',JSON.stringify({
        'tabList':state.tabList,
        'activeTab':state.activeTab
      }))
    },
    initTabList(state,tabObj){
      state.tabList = tabObj.tabList;
      state.activeTab = tabObj.activeTab;
      sessionStorage.setItem('tabObject',JSON.stringify({
        'tabList':state.tabList,
        'activeTab':state.activeTab
      }))
    },
    //设置菜单到store里面
    setMenuList(state, list) {
      state.menuList = list;
    },
    //设置路由到store
    setRouterList(state, list){
      state.routerList = list;
    },
    //动态路由生成
    dynamicRouter(state, router) {
      let oldRouter = router.options.routes;
      let routerList = state.routerList;
      routerList.forEach(item => {
        if (/^.+\.html$/ig.test(item.url)) {
          console.log('进入iframe路由')
          item.component = resolve => require([`@/views/IFrame/IFrame.vue`], resolve);
        } else {
          // item.component = () => import(`@/views${item.url}.vue`);
          item.component =(resolve) => require([`@/views${item.url}.vue`],resolve);
        }
        oldRouter[2].children.push(item);
      })
      //5.添加到现有路由里面
      router.addRoutes(oldRouter);
    }
  },
  actions: {
    async getMenuList(content,router){
      // console.log(router)
      let res = await getMenuList();
      console.log(res);
      let menuList = res.data.data.menuList;
      let routerList = res.data.data.routerList;
      content.commit('setMenuList',menuList);
      content.commit('setRouterList',routerList);
      content.commit('dynamicRouter',router);
    }
  },
  modules: {
  }
})
